package main

import (
	"bytes"

	"context"
	"encoding/json"
	"fmt"
	redis "github.com/go-redis/redis/v8"
	"github.com/sony/sonyflake"
	"google.golang.org/protobuf/proto"
	"io"
	"net/http"
	"os"
	"trpc.group/trpc-go/trpc-go"
	"trpc.group/trpc-go/trpc-go/log"
	_ "trpc.group/trpc-go/trpc-naming-consul"
	_ "trpc.group/trpc-go/trpc-opentelemetry/oteltrpc"
	pb "trpcdemo/proto"
)

var (
	//redis的地址
	redisAddr = getenv("REDIS_ADDR", "127.0.0.1:6379")
	//consul地址
	consulAddr = getenv("CONSUL_ADDR", "127.0.0.1:8500")
	//http服务器监听地址和端口
	httPort = getenv("HTTP_PORT", "9001")
	//要暴露的服务ip地址
	hostIp = getenv("HOST_IP", "127.0.0.1") //docker宿主机ip
	//trpc端口
	trpcPort = getenv("TRPC_PORT", "9002")
)

func getenv(key, defaultValue string) string {
	if value, exists := os.LookupEnv(key); exists {
		return value
	}
	return defaultValue
}

func init() {

}

type DataServiceService struct{}

var redisClient *redis.Client

func main() {
	redisClient = redis.NewClient(&redis.Options{
		Addr: redisAddr,
	})
	s := trpc.NewServer()
	pb.RegisterDataServiceService(s, &DataServiceService{})
	log.Info("监听RPC端口:", trpcPort)
	if err := s.Serve(); err != nil {
		log.Fatal(err)
	}
}

func (g DataServiceService) ProcessData(ctx context.Context, req *pb.Mydata) (*pb.ProcessDataRequest, error) {
	log.Info("接收到RPC请求: %s", req)
	log.Info("RedisKey生成中......")
	//生成rediskey
	flake := sonyflake.NewSonyflake(sonyflake.Settings{})
	id, err := flake.NextID()
	if err != nil {
		log.Error(err)
	}
	key := fmt.Sprintf("process_data_%d", id)
	value, _ := proto.Marshal(req)
	ctx = context.Background()
	err = redisClient.Set(ctx, key, value, 0).Err()
	if err != nil {
		log.Error(err)
		return nil, err
	}
	log.Info("Redis写入成功")
	//http调用
	data := map[string]interface{}{
		"redisKey": key,
	}
	jsonData, _ := json.Marshal(data)
	resp, err := http.Post(
		"http://127.0.0.1:8081/greeting_java",
		"application/json",
		bytes.NewBuffer(jsonData),
	)
	if err != nil {
		fmt.Println("请求出错:", err)
		return nil, err
	}
	defer resp.Body.Close()
	// 4. 读取响应内容
	body, _ := io.ReadAll(resp.Body)

	//解码输出
	&pb.ProcessDataResponse = body
	fmt.Println("响应结果:", bodyjson.con)
	return &pb.ProcessDataRequest{RedisKey: key}, nil
}
